<template>
  <view class="calendar-container">
    <!-- 月份选择器 -->
    <view class="month-selector">
      <view class="month-nav" @click="previousMonth">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <view class="current-month">{{ currentMonthText }}</view>
      <view class="month-nav" @click="nextMonth">
        <uni-icons type="right" size="20" color="#333"></uni-icons>
      </view>
    </view>

    <!-- 星期标题 -->
    <view class="weekday-header">
      <view
        v-for="day in weekDays"
        :key="day"
        class="weekday-cell"
        :class="{
          weekend: day === '日' || day === '六',
        }"
      >
        {{ day }}
      </view>
    </view>

    <!-- 日历网格 -->
    <view class="calendar-grid">
      <view
        v-for="(day, index) in calendarDays"
        :key="index"
        class="calendar-cell"
        :class="{
          'other-month': !day.isCurrentMonth,
          today: day.isToday,
          weekend: day.isWeekend,
          'has-schedule': day.hasSchedule,
        }"
        @click="handleDayClick(day)"
      >
        <!-- 日期 -->
        <view class="date-number" :class="{ holiday: day.isWeekend }">
          {{ day.date }}
        </view>

        <!-- 排班信息 -->
        <view v-if="day.hasSchedule && day.scheduleInfo" class="schedule-info">
          <!-- 考勤结果 -->
          <view
            v-if="day.scheduleInfo.attendanceResult"
            class="attendance-result"
            :class="getAttendanceBadgeClass(day.scheduleInfo.attendanceResult)"
          >
            {{ day.scheduleInfo.attendanceResult }}
          </view>
        </view>

        <!-- 无排班标记 -->
        <view v-else-if="day.isCurrentMonth" class="schedule-info">
          <view class="no-schedule-mark">无排班</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import type { IAttendanceRecord } from "../api/interface";

interface DayInfo {
  date: number;
  fullDate: string;
  isCurrentMonth: boolean;
  isToday: boolean;
  isWeekend: boolean;
  hasSchedule: boolean;
  scheduleInfo?: {
    id: string;
    shiftGroupName: string;
    timeRange: string;
    attendanceResult: string;
    color: string;
    record: IAttendanceRecord;
  };
}

interface Props {
  scheduleData?: IAttendanceRecord[];
}

const props = withDefaults(defineProps<Props>(), {
  scheduleData: () => [],
});

const emit = defineEmits<{
  (e: "monthChange", year: number, month: number): void;
  (e: "dayClick", day: DayInfo): void;
}>();

// 星期标题
const weekDays = ["日", "一", "二", "三", "四", "五", "六"];

// 当前年月
const currentYear = ref<number>(new Date().getFullYear());
const currentMonth = ref<number>(new Date().getMonth() + 1);

// 当前月份文本
const currentMonthText = computed(() => {
  return `${currentYear.value} 年 ${currentMonth.value} 月`;
});

// 生成日历数据
const calendarDays = computed(() => {
  const days: DayInfo[] = [];
  const year = currentYear.value;
  const month = currentMonth.value;

  // 当前月第一天
  const firstDay = new Date(year, month - 1, 1);
  const firstDayWeekday = firstDay.getDay();

  // 当前月天数
  const daysInMonth = new Date(year, month, 0).getDate();

  // 上个月天数
  const prevMonthDays = new Date(year, month - 1, 0).getDate();

  // 今天日期
  const today = new Date();
  const todayStr = `${today.getFullYear()}-${String(
    today.getMonth() + 1,
  ).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;

  // 填充上个月的日期
  for (let i = firstDayWeekday - 1; i >= 0; i--) {
    const date = prevMonthDays - i;
    const prevMonth = month === 1 ? 12 : month - 1;
    const prevYear = month === 1 ? year - 1 : year;
    const fullDate = `${prevYear}-${String(prevMonth).padStart(
      2,
      "0",
    )}-${String(date).padStart(2, "0")}`;

    days.push({
      date,
      fullDate,
      isCurrentMonth: false,
      isToday: false,
      isWeekend: false,
      hasSchedule: false,
    });
  }

  // 填充当前月的日期
  for (let date = 1; date <= daysInMonth; date++) {
    const fullDate = `${year}-${String(month).padStart(2, "0")}-${String(
      date,
    ).padStart(2, "0")}`;
    const dayOfWeek = new Date(year, month - 1, date).getDay();
    const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
    const isToday = fullDate === todayStr;

    // 查找该日期的排班信息
    const scheduleRecord = props.scheduleData.find(
      (record) => {
        // 处理可能的日期格式差异
        const recordDate = record.ShiftDate?.split('T')[0] || record.ShiftDate;
        return recordDate === fullDate;
      }
    );

    const dayInfo: DayInfo = {
      date,
      fullDate,
      isCurrentMonth: true,
      isToday,
      isWeekend,
      hasSchedule: !!scheduleRecord,
    };

    if (scheduleRecord) {
      // 提取工作时间范围
      let timeRange = "";
      if (scheduleRecord.WorkStartTime && scheduleRecord.WorkEndTime) {
        // 使用 WorkStartTime 和 WorkEndTime
        timeRange = `${scheduleRecord.WorkStartTime.substring(0, 5)}-${scheduleRecord.WorkEndTime.substring(0, 5)}`;
      } else if (
        scheduleRecord.ShiftDetails &&
        scheduleRecord.ShiftDetails.length > 0
      ) {
        // 后备方案：使用 ShiftDetails
        const firstShift = scheduleRecord.ShiftDetails[0];
        timeRange = `${firstShift.StartTime.substring(0, 5)}-${firstShift.WorkEndTime.substring(0, 5)}`;
      }

      // 获取颜色
      let color = "#1890ff";
      if (
        scheduleRecord.ShiftDetails &&
        scheduleRecord.ShiftDetails.length > 0
      ) {
        color =
          scheduleRecord.ShiftDetails[0].DisplayColor || color;
      }

      dayInfo.scheduleInfo = {
        id: scheduleRecord.ID,
        shiftGroupName: scheduleRecord.AttendanceShiftGroupName || "排班",
        timeRange,
        attendanceResult: scheduleRecord.AttendanceResult || "",
        color,
        record: scheduleRecord,
      };
    }

    days.push(dayInfo);
  }

  // 填充下个月的日期，确保总共6行（42个格子）
  const remainingDays = 42 - days.length;
  for (let date = 1; date <= remainingDays; date++) {
    const nextMonth = month === 12 ? 1 : month + 1;
    const nextYear = month === 12 ? year + 1 : year;
    const fullDate = `${nextYear}-${String(nextMonth).padStart(
      2,
      "0",
    )}-${String(date).padStart(2, "0")}`;

    days.push({
      date,
      fullDate,
      isCurrentMonth: false,
      isToday: false,
      isWeekend: false,
      hasSchedule: false,
    });
  }

  return days;
});

// 上一月
const previousMonth = () => {
  if (currentMonth.value === 1) {
    currentYear.value--;
    currentMonth.value = 12;
  } else {
    currentMonth.value--;
  }
  emit("monthChange", currentYear.value, currentMonth.value);
};

// 下一月
const nextMonth = () => {
  if (currentMonth.value === 12) {
    currentYear.value++;
    currentMonth.value = 1;
  } else {
    currentMonth.value++;
  }
  emit("monthChange", currentYear.value, currentMonth.value);
};

// 点击日期
const handleDayClick = (day: DayInfo) => {
  if (day.isCurrentMonth) {
    emit("dayClick", day);
  }
};

// 获取考勤结果徽章样式
const getAttendanceBadgeClass = (result: string) => {
  // 正常、请假、休假 - 绿色
  if (result === "正常" || result === "请假" || result === "休假") {
    return "badge-success";
  }
  // 迟到、早退、迟到且早退 - 橙色
  else if (result === "迟到" || result === "早退" || result === "迟到且早退") {
    return "badge-warning";
  }
  // 旷工、缺卡、缺勤、出勤 - 红色
  else if (result === "旷工" || result === "缺卡" || result === "缺勤" || result === "出勤") {
    return "badge-error";
  }
  // 未计算等其他状态 - 灰色
  return "badge-default";
};

// 监听月份变化，触发事件
watch(
  [currentYear, currentMonth],
  () => {
    // 初始化时不触发
  },
  { immediate: false },
);
</script>

<style lang="scss" scoped>
.calendar-container {
  width: 100%;
  background: #ffffff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.month-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  .month-nav {
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    transition: all 0.3s ease;

    &:active {
      background: rgba(255, 255, 255, 0.3);
      transform: scale(0.95);
    }
  }

  .current-month {
    font-size: 18px;
    font-weight: 600;
    color: #ffffff;
    letter-spacing: 1px;
  }
}

.weekday-header {
  display: flex;
  background: #f5f7fa;
  border-bottom: 1px solid #e8eaed;

  .weekday-cell {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    font-size: 14px;
    font-weight: 500;
    color: #606266;

    &.weekend {
      color: #f56c6c;
    }
  }
}

.calendar-grid {
  display: flex;
  flex-wrap: wrap;

  .calendar-cell {
    width: calc(100% / 7);
    min-height: 70px;
    border-right: 1px solid #e8eaed;
    border-bottom: 1px solid #e8eaed;
    padding: 6px;
    box-sizing: border-box;
    position: relative;
    background: #ffffff;
    transition: all 0.2s ease;
    display: flex;
    flex-direction: column;
    align-items: center;

    &:nth-child(7n) {
      border-right: none;
    }

    &.other-month {
      background: #f9f9f9;
      opacity: 0.5;
    }

    &.today {
      background: #fff7e6;
    }

    &.weekend:not(.other-month) {
      background: #fef9f9;
    }

    &.has-schedule:not(.other-month) {
      background: #f0f7ff;
    }

    &:active:not(.other-month) {
      background: #e6f7ff;
    }

    .date-number {
      font-size: 14px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 4px;

      &.holiday {
        color: #f56c6c;
      }
    }

    .schedule-info {
      display: flex;
      align-items: center;
      justify-content: center;
      flex: 1;
      width: 100%;

      .attendance-result {
        width: 100%;
        text-align: center;
        padding: 4px 2px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 500;
        line-height: 1.2;

        &.badge-success {
          background: #e7f9f0;
          color: #52c41a;
        }

        &.badge-warning {
          background: #fff7e6;
          color: #faad14;
        }

        &.badge-error {
          background: #fff1f0;
          color: #ff4d4f;
        }

        &.badge-default {
          background: #f0f0f0;
          color: #666;
        }
      }
    }

    .no-schedule-mark {
      width: 100%;
      text-align: center;
      padding: 4px 2px;
      border-radius: 4px;
      font-size: 11px;
      font-weight: 500;
      line-height: 1.2;
      background: #f5f5f5;
      color: #999;
    }
  }
}
</style>

